package com.zjw.utils;

import com.zjw.config.ConfigManager;

import java.sql.*;

/**
 * @projectName: Chapter8
 * @package: utils
 * @className: ConnectionUtil
 * @author: 翟
 * @date: 2025/3/31 2:05
 */

public class ConnectionUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        driver = ConfigManager.getProperty("driver");
        url = ConfigManager.getProperty("url");
        username = ConfigManager.getProperty("user");
        password = ConfigManager.getProperty("password");
//Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
// 这个警告信息表明，你正在使用旧的 MySQL JDBC 驱动类 com.mysql.jdbc.Driver，这个类已经被弃用。新的驱动类是 com.mysql.cj.jdbc.Driver，并且这个驱动类会通过 SPI（Service Provider Interface）自动注册，因此通常不需要手动加载驱动类。
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("加载驱动失败");
        }
    }

    //连接数据库返回Connection
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url , username , password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭数据库连接、SQL语句和结果集对象

    /**
     * 关闭数据库连接、SQL语句和结果集对象
     * @param resultSet 结果集对象
     * @param statement SQL语句
     * @param conn 数据库连接
     */
    public static void closeALL(ResultSet resultSet , Statement statement , Connection conn ){
        try {
            //关闭结果集对象
            if (resultSet != null){
                resultSet.close();
            }
            //关闭SQL语句对象
            if (statement != null){
                statement.close();
            }
            //关闭数据库连接
            if (conn != null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }




}
